<template>
  <div>
    <h1>购物车管理</h1><hr>
    <el-table
        :data="tableData"
        border
        show-summary
        style="width: 100%">
      <el-table-column
          prop="orderNumber"
          label="商品编码"
          width="180">
      </el-table-column>
      <el-table-column
          prop="cropName"
          label="商品名称"
          width="180">
      </el-table-column>
      <el-table-column
          prop="buyNum"
          sortable
          label="购买的数量"
          width="230">
        <template v-slot="scope">
          <el-input-number v-model="scope.row.buyNum" @change="changeBuyNum(scope.row.buyNum,scope.row.id)" :min="0" :max="10" label="描述文字"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
          prop="price"
          sortable
          label="金额"
          width="230">
        <template v-slot="scope">
          {{scope.row.price}} 元
        </template>
      </el-table-column>
    </el-table>
    <div><hr>
      <el-button @click="buyGoods" type="primary" size="small">立即购买</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "CartView",
  data(){
    return{
      tableData:[]
    }
  },methods:{
    /*购物车列表*/
    cartList(){
      this.axios.post("http://172.20.10.5:8003/api/tb-cart/cartList").then(res=>{
        this.tableData=res.data
      })
    },changeBuyNum(buyNum,id){
      //如果购买数量为0时删掉购物车里的该商品
      if(buyNum==0){
        this.axios.post("http://172.20.10.5:8003/api/tb-cart/getByBuyNumDelCart?id="+id).then(res=>{
            this.cartList();
        })
      }
      //如何购买数量不为0时随着购买数量而改变金额
      this.axios.post("http://172.20.10.5:8003/api/tb-cart/changeBuyNum?buyNum="+buyNum+"&id="+id).then(res=>{
        if(res.data=="success"){
          this.cartList();
        }
        else{
          this.$message.error("库存不足");
        }
      })
    },// 立即购买
    buyGoods(){
        this.axios.post("http://172.20.10.5:8003/api/tb-cart/buyGoods").then(res=>{
          if(res.data.msg=="success"){
            //去支付
            this.axios.post("http://172.20.10.5:8003/api/pay-plan/toPay?outTradeNo="+res.data.outTradeNo).then(res=>{
              if(res.data=="error"){
                this.$message.error("调用支付失败！！")
              }
              let win = window.open("#","_blank");
              win.document.writeln(res.data);
            })
          }
        })
    },
  },created() {
    this.cartList();
  }
}
</script>

<style scoped>

</style>